<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
	модуль новостей



*/

class News extends CI_Model {

	public $module_name = 'Модуль новостей';
	public $module_subfunctions = array (
	 		'channels' => 'Конфигурация каналов'
		);

	public $last_error  = '';
	public $last_mesg   = '';

	private $table_news     = 'foria_module_news';
	private $table_channels = 'foria_module_news_channels';

    function __construct()
    {
        parent::__construct();
		$this->load->helper('directory');
		$this->tools_folder =  BASEPATH."../application/modules/";
    }

	function admin()
	{
		$data = array ();
		//print_r ($_REQUEST);
		isset($_REQUEST['act'])?$act=$_REQUEST['act']:$act='';
		isset($_REQUEST['cmd'])?$cmd=$_REQUEST['cmd']:$cmd='';

		if ($cmd)
		{
			$ret = $this->admin_process_cmd($cmd);
			if ($ret == true)
			{
				$act = '';
			}
		}

		$data ['error'] = $this->last_error;
		$data ['mesg'] = $this->last_mesg;
		$data ['request'] = $_REQUEST;

		$data['browse'] = $this->_calculate_limit($this->table_news);
		$data['channels'] = $this->_fetch_channels ();

		$this->load->view('modules/news/header', $data);

		switch ($act)
		{
			case 'new':
				$this->load->view('modules/news/news', $data);
				break;
			case 'edit_news':
				$this->db->where('id', (int)$_REQUEST['id']);
				$query = $this->db->get($this->table_news);
				if ($row = $query->result_array())
				{
					$data['request'] = $row[0];
					//print_r ($data);
					$this->load->view('modules/news/news', $data);
					break;
				}
				$data ['error'] = 'Запись для редактирования не найдена.';
			default:
				$this->load->view('modules/news/navigation', $data);
				$this->admin_browse($data['browse']);
				break;

		}


		$this->load->view('modules/news/footer', $data);
	}

	private function _fetch_channels()
	{
		$ret = array ();
		$this->db->order_by('name ASC');
		$this->db->select('name');
		$query = $this->db->get($this->table_channels);
		if ($query->num_rows()>0)
		{
			foreach ($query->result_array() as $row)
			{
				$ret[] = $row['name'];
			}
		}
		return $ret;
	}


	private function _calculate_limit($table)
	{

		isset($_REQUEST['act'])?$act=$_REQUEST['act']:$act='';

		isset($_REQUEST['step'])?$step=(int)$_REQUEST['step']:$step=20;
		isset($_REQUEST['start'])?$start=(int)$_REQUEST['start']:$start=0;

		if (isset($_REQUEST['channel']) && $_REQUEST['channel']!='')
		{
			$this->db->where(array('channel'=>$_REQUEST['channel']));
		}

		$total = $this->db->count_all_results($table);

		switch ($act)
		{
			case 'next':
				$start += $step;
				if ($start > $total)
					$start = $total - $total%$step;
				if ($start == $total)
					$start = $total - 1;
				break;
			case 'last':
				$start = $total - $total%$step;
				if ($start == $total)
					$start -= 1;
				break;
			case 'first':
				$start = 0;
				break;
			case 'prev':
				$start -= $step;
				if ($start < 0)
					$start = 0;
				break;
			case 'new':
				$start = 0;
				break;
		}

		$data['start'] = $start;
		$data['step']  = $step;
		$data['total'] = $total;

		return $data;

	}


	private function admin_browse($data)
	{

		$this->load->view('modules/news/browse_head');

		if (isset($_REQUEST['channel']) && $_REQUEST['channel']!='')
		{
			$this->db->where(array('channel'=>$_REQUEST['channel']));
		}

		$this->db->order_by('date DESC');
		$this->db->limit($data['step'], $data['start']);
		$this->db->select('id, title, short, date, active, channel');
		$query = $this->db->get($this->table_news);
		if ($query->num_rows()>0)
		{
			foreach ($query->result_array() as $row) {
				$this->load->view('modules/news/browse_body', $row);
			}
		} else {
			$this->load->view('modules/news/browse_empty');
		}

		$this->load->view('modules/news/browse_foot');

	}


	private function admin_process_cmd($cmd)
	{
		$ret = true;
		switch ($cmd)
		{
			case 'create_news':
				$ret = $this->admin_create_news();
				break;
			case 'del_news':
				$ret = $this->admin_del_news();
				break;
		}

		return $ret;
	}

	private function _is_exists ($a_where, $table)
	{
		$this->db->where($a_where);
		$this->db->select('id');
		$query = $this->db->get($table);
		if ($query->num_rows() > 0)
			return true;
		return false;
	}

	private function admin_del_news()
	{
		$id = (int)($_REQUEST['id']);
		if ($this->_is_exists(array('id' => $id), $this->table_news)==false) {
			$this->last_error = 'Новость уже удалена';
			return false;
		}
		$this->db->where('id', $id);
		$this->db->delete($this->table_news);
		$this->last_mesg = 'Новость удалена.';
		return true;
	}

	private function admin_create_news()
	{

		$title = $_REQUEST ['title'];
		if (empty($title))
		{
			$this->last_error='Название новости не может быть пустой';
			return false;
		}
		$channel = $_REQUEST ['channel'];
		if (empty($channel))
		{
			$this->last_error='Канал для новости должен быть задан.';
			return false;
		}
		$date = $_REQUEST ['date'];
		if (empty($date) || preg_match("/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?$/", $date) == false)
		{
			$this->last_error='Дата не определена или не верный формат даты.';
			return false;
		}
		$short = $_REQUEST ['short'];
		if (empty($short))
		{
			$this->last_error='Кратко не может быть пустым';
			return false;
		}
		$full = $_REQUEST ['full'];

		isset($_REQUEST['id'])?$id=(int)$_REQUEST['id']:$id=0;

		$md5 = md5($title.":".$short.":".$full);
		if ($id > 0)
		{
			$where = array ('md5' => $md5, 'id <>' => $id);
		}
		else
		{
			$where = array ('md5' => $md5);
		}

		if ($this->_is_exists($where, $this->table_news)==true) {
			$this->last_error = 'Не могу создать новость, подобная новость уже существует.';
			return false;
		}

		$data = array (
			'title' => $title,
			'date'	=> $date,
			'active'	=> isset($_REQUEST['active'])&&$_REQUEST['active']!=''?'true':'false',
			'short'	=> $short,
			'channel' => $channel,
			'full'	=> $full,
			'created' => date ('Y-m-d H:i', time()),
			'md5' => $md5
		);

		if ($id > 0)
		{
			$data['updated'] = date ('Y-m-d H:i', time());
			unset($data['created']);
			$this->db->where('id', $id);
			$this->db->update($this->table_news, $data);
			$this->last_mesg = 'Новость сохранена.';
		}
		else
		{
			$this->db->insert($this->table_news, $data);
			$this->last_mesg = 'Новая новость создана.';
		}

		return true;

	}

	function channels()
	{
		$data = array ();
		//print_r ($_REQUEST);
		isset($_REQUEST['act'])?$act=$_REQUEST['act']:$act='';
		isset($_REQUEST['cmd'])?$cmd=$_REQUEST['cmd']:$cmd='';

		if ($cmd)
		{
			$ret = $this->channels_process_cmd($cmd);
			if ($ret == true)
			{
				$act = '';
			}
		}

		$data ['error'] = $this->last_error;
		$data ['mesg'] = $this->last_mesg;
		$data ['request'] = $_REQUEST;

		$data['browse'] = $this->_calculate_limit($this->table_channels);

		$this->load->view('modules/news/channels/header', $data);

		switch ($act)
		{
			case 'new':
				$this->load->view('modules/news/channels/channel', $data);
				break;
			case 'edit_channel':
				$this->db->where('id', (int)$_REQUEST['id']);
				$query = $this->db->get($this->table_channels);
				if ($row = $query->result_array())
				{
					$data['request'] = $row[0];
					$this->load->view('modules/news/channels/channel', $data);
					break;
				}
				$data ['error'] = 'Запись для редактирования не найдена.';
			default:
				$this->load->view('modules/news/channels/navigation', $data);
				$this->channels_browse($data['browse']);
				break;

		}


		$this->load->view('modules/news/channels/footer', $data);
	}

	private function channels_browse($data)
	{

		$this->load->view('modules/news/channels/browse_head');

		$this->db->order_by('name ASC');
		$this->db->limit($data['step'], $data['start']);
		$this->db->select('id, name, title, description, active, created');
		$query = $this->db->get($this->table_channels);
		if ($query->num_rows()>0)
		{
			foreach ($query->result_array() as $row) {
				$this->load->view('modules/news/channels/browse_body', $row);
			}
		}
		else
		{
			$this->load->view('modules/news/channels/browse_empty');
		}

		$this->load->view('modules/news/channels/browse_foot');

	}

	private function channels_process_cmd($cmd)
	{
		$ret = true;
		switch ($cmd)
		{
			case 'create_channel':
				$ret = $this->channels_create_channel();
				break;
			case 'del_channel':
				$ret = $this->channels_del_channel();
				break;
		}

		return $ret;
	}

	private function channels_create_channel()
	{

		$name = $_REQUEST ['name'];
		if (empty($name))
		{
			$this->last_error='Имя канала (идентификатор) не может быть пустым';
			return false;
		}
		$title = $_REQUEST ['title'];
		if (empty($title))
		{
			$this->last_error='Название канала не может быть пустым';
			return false;
		}
		$description = $_REQUEST ['description'];

		isset($_REQUEST['id'])?$id=(int)$_REQUEST['id']:$id=0;

		//$md5 = md5($name);
		if ($id > 0)
		{
			$where = array ('name' => $name, 'id <>' => $id);
		}
		else
		{
			$where = array ('name' => $name);
		}

		if ($this->_is_exists($where, $this->table_channels)==true) {
			$this->last_error = 'Не могу создать канал, подобный канал уже существует.';
			return false;
		}

		$data = array (
			'name' => $name,
			'title' => $title,
			'description' => $description,
			'active'	=> isset($_REQUEST['active'])&&$_REQUEST['active']!=''?'true':'false',
			'created' => date ('Y-m-d H:i', time()),
			//'md5' => $md5
		);

		if ($id > 0)
		{
			$data['updated'] = date ('Y-m-d H:i', time());
			unset($data['created']);
			$this->db->where('id', $id);
			$this->db->update($this->table_channels, $data);
			$this->last_mesg = 'Канал сохранен.';
		}
		else
		{
			$this->db->insert($this->table_channels, $data);
			$this->last_mesg = 'Новый канал создан.';
		}

		return true;

	}

	private function channels_del_channel()
	{
		$id = (int)($_REQUEST['id']);
		if ($this->_is_exists(array('id' => $id), $this->table_channels)==false) {
			$this->last_error = 'Канал уже удален';
			return false;
		}
		$this->db->where('id', $id);
		$this->db->delete($this->table_channels);
		$this->last_mesg = 'Канал удален.';
		return true;
	}

	private function _view_set_where ($channels, $where)
	{
		$this->db->where('active', 'true');
		if (!empty($where))
		{
			$this->db->where($where);
		}
		if (!empty($channels))
		{
			$t = explode(',', $channels);
			$this->db->where_in('channel', $t);
		}
	}

	private function _view_channels ()
	{

		$ret = array();
		$ret['data'] = array();
		$this->db->order_by('name');
		$this->db->where('active', 'true');
		$query = $this->db->get($this->table_channels);
		if ($query->num_rows()>0)
		{
			foreach ($query->result_array() as $row) {
				$ret['data'][] = $row;
			}
		}

		return $ret;

	}



	function view($page = 1, $step = 10, $show = 5,
					$channels = "", $fields = "date, title, short", $order = "date DESC", $where = "",
					$channels_only=false, $check_next = false)
	{

		if ($channels_only == true)
		{
			return $this->_view_channels();
		}

		$ret = array();
		$ret['data'] = array();
		$ret['pagination'] = array();

		$this->_view_set_where ($channels, $where);

		$total = $this->db->count_all_results($this->table_news);

		//print $where." ".$total; exit;

		if ($page < 0)
		{
			header ('Location: '.$_SERVER["PHP_SELF"]."/404");
			exit;
		}

		if ($page < 0)
		{
			header ('Location: '.$_SERVER["PHP_SELF"]."/404");
			exit;
		}

		$start = ($page - 1) * $step;

		if ($start >= $total)
		{
			header ('Location: '.$_SERVER["PHP_SELF"]."/404");
			exit;
			$start = (ceil($total/$step) - 1) *$step;
		}
		if ($start < 0 )
			$start = 0;

		//print ($start);

		$this->_view_set_where ($channels, $where);
		$this->db->order_by($order);
		$this->db->order_by('id DESC');
		$this->db->limit($step, $start);

		if ($check_next == true)
			$fields .= ',id';

		$this->db->select($fields);

		$query = $this->db->get($this->table_news);

		if ($query->num_rows()>0)
		{
			foreach ($query->result_array() as $row) {
				$ret['data'][] = $row;
			}
		}

		if ($check_next == true)
		{
			$pagination = array ('prev'=>'', 'next'=>'');

			if (isset($ret['data'][0])&&$ret['data'][0]['id'] > 0)
			{
				// get next record
				$this->_view_set_where ($channels, 'id <' . $ret['data'][0]['id']);
				$this->db->order_by($order);
				$this->db->order_by('id DESC');
				$this->db->limit(1, 0);
				$this->db->select($fields);
				$query = $this->db->get($this->table_news);
				if ($row = $query->result_array())
				{
					$pagination['next'] = $row[0];
				}

				// get prev record
				$this->_view_set_where ($channels, 'id >' . $ret['data'][0]['id']);
				$total = $this->db->count_all_results($this->table_news);
				if ($total > 0) $total -= 1;
				$this->_view_set_where ($channels, 'id >' . $ret['data'][0]['id']);
				$this->db->order_by($order);
				$this->db->order_by('id DESC');
				$this->db->limit(1, $total);
				$this->db->select($fields);
				$query = $this->db->get($this->table_news);
				if ($row = $query->result_array())
				{
					$pagination['prev'] = $row[0];
				}
			}
			$ret['pagination'] = $pagination;
		}
		else
		{
			$this->load->helper('pagination');
			$ret['pagination'] = pagination($total, $step, $page, $show);
		}

		return $ret;

	}

}


